package smartcase.config.auth;

import com.google.common.base.Strings;
import smartcase.base.auth.AbstractCookieCredentialFunction;
import smartcase.base.auth.AbstractHeaderCredentialFunction;
import smartcase.base.auth.Credential;
import smartcase.base.auth.TokenFlag;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public class DefaultTokenVerify
    implements AbstractHeaderCredentialFunction, AbstractCookieCredentialFunction {

  private String cookieName;
  private String headerKey;
  private final TokenFlag flag;

  public DefaultTokenVerify(TokenFlag flag, String flagValue) {
    this.flag = flag;
    if (TokenFlag.COOKIE.equals(flag)) cookieName = flagValue;
    if (TokenFlag.HEADER.equals(flag)) headerKey = flagValue;
    if (Strings.isNullOrEmpty(flagValue)) {
      throw new RuntimeException("auth config?");
    }
  }

  @Override
  public String getHeaderKey() {
    return headerKey;
  }

  @Override
  public Credential verify(HttpServletRequest request) {
    if (TokenFlag.COOKIE.equals(flag)) {
      return AbstractCookieCredentialFunction.super.verify(request);
    }
    if (TokenFlag.HEADER.equals(flag)) {
      return AbstractHeaderCredentialFunction.super.verify(request);
    }
    throw new RuntimeException("error auth config");
  }

  @Override
  public Credential mapHeaderValueToCredential(HttpServletRequest request, String headerValue) {
    return Credential.INVALID_CREDENTIAL;
  }

  @Override
  public String getCookieName() {
    return cookieName;
  }

  @Override
  public Credential mapCookieToCredential(HttpServletRequest request, Cookie cookie) {
    return null;
  }
}
